package com.lele.config;

import com.lele.domain.Permission;
import com.lele.domain.Role;
import com.lele.filter.CaptchaFilter;
import com.lele.service.AdminUserDetailsService;
import com.lele.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.List;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private PermissionService permissionService;
    @Autowired
    private CaptchaFilter captchaFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        List<Permission> permissions = permissionService.getAllPermission();

        // 通过ExpressionInterceptUrlRegistry来注册url及添加url对主应的角色
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry urlRegistry = http.authorizeRequests();

        for (Permission permission : permissions) {
            List<Role> roles = permission.getRoles();

            String[] roleArray = new String[roles.size()];
            for (int i = 0; i < roleArray.length; i++) {
                roleArray[i] = roles.get(i).getRoleDesc().substring(5);
            }

            urlRegistry.antMatchers(permission.getPermName()).hasAnyRole(roleArray);
        }

        urlRegistry
                .antMatchers("/captcha").permitAll()
                .and()
                .formLogin()
                .loginPage("/userLogin")
                .loginProcessingUrl("/checkLogin")
                .defaultSuccessUrl("/main")
                .permitAll()
                .and()
                .addFilterBefore(captchaFilter, UsernamePasswordAuthenticationFilter.class)
                .logout().permitAll();

    }
    @Bean
    @Override
    protected UserDetailsService userDetailsService(){
        return new AdminUserDetailsService();
    }
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
